package com.snda.game.legend.dao;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;

import com.snda.game.legend.entiy.Ad;

@Repository
public class AdDao extends BaseDao<Ad> {

    public Map<Integer, List<Ad>> getAllEnableAds() {
        Map<Integer, List<Ad>> map = new HashMap<Integer, List<Ad>>();
        Session session = getSession();
        for (int i = 1; i <= 4; i++) {
            Criteria criteria = session.createCriteria(Ad.class);
            criteria.add(Restrictions.eq("enable", 1))
                    .add(Restrictions.eq("index", i))
                    .addOrder(Order.desc("weight"));
            List<Ad> list = query(criteria);
            if (list != null && list.size() > 0) {
                map.put(i, list);
            }
        }
        releaseSession(session);
        return map;
    }

    public Map<Integer, List<Ad>> getAllAds() {
        Map<Integer, List<Ad>> map = new HashMap<Integer, List<Ad>>();
        Session session = getSession();
        for (int i = 1; i <= 4; i++) {
            Criteria criteria = session.createCriteria(Ad.class);
            criteria.add(Restrictions.eq("index", i)).addOrder(
                    Order.desc("weight"));
            List<Ad> list = query(criteria);
            if (list != null && list.size() > 0) {
                map.put(i, list);
            }
        }
        releaseSession(session);
        return map;
    }

    public void expired() {

        Session session = getSession();
        Criteria criteria = session.createCriteria(Ad.class);
        Date now = new Date();
        criteria.add(Restrictions.le("begintime", now)).add(
                Restrictions.ge("endtime", now));
        List<Ad> nextAds = query(criteria);
        for (Ad ad : nextAds) {
            ad.setEnable(1);
            update(ad);
        }
        criteria = session.createCriteria(Ad.class);
        criteria.add(Restrictions.le("endtime", now));
        List<Ad> previousAds = query(criteria);
        for (Ad ad : previousAds) {
            ad.setEnable(0);
            update(ad);
        }
        releaseSession(session);

    }

}
